package study.jdk.bytecode.javassist.echo;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.Modifier;

import java.lang.reflect.Method;

public class EchoMain {

    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        //创建类 classname：创建类路径和名称
        CtClass ctClass = pool.makeClass("study.jdk.bytecode.javassist.echo.Echo");
        //添加方法
        CtMethod mainMethod = new CtMethod(CtClass.voidType,
                "main",
                new CtClass[]{pool.get(String[].class.getName())},
                ctClass);
        mainMethod.setModifiers(Modifier.PUBLIC + Modifier.STATIC);
        mainMethod.setBody("{System.out.println(\"javassist hi helloworld by 小傅哥(bugstack.cn)\");}");
        ctClass.addMethod(mainMethod);

        //创建无参数构造方法
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);
        ctConstructor.setBody("{}");
        ctClass.addConstructor(ctConstructor);

        //输出类内容
        ctClass.writeFile();

        //调用
        Class clazz = ctClass.toClass();
        Object obj = clazz.newInstance();

        Method main = clazz.getDeclaredMethod("main", String[].class);
        main.invoke(obj, (Object) new String[1]);
    }
}
